pub use super::_entities::sea_orm_active_enums::Type;
pub use super::_entities::tax_rates::{self, ActiveModel, Entity, Model};
use loco_rs::prelude::*;
use rust_decimal::Decimal;
use sea_orm::DeleteResult;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

#[derive(Debug, Deserialize, Serialize)]
pub struct CreateParams {
    pub region_id: String,
    pub name: String,
    pub r#type: Type,
    pub rate: Decimal,
}

#[derive(Debug, Validate, Deserialize)]
pub struct Validator {
    #[validate(length(min = 1, message = "Region ID must not be empty."))]
    pub region_id: String,
    #[validate(length(min = 1, message = "Name must not be empty."))]
    pub name: String,
}

impl Validatable for ActiveModel {
    fn validator(&self) -> Box<dyn Validate> {
        Box::new(Validator {
            region_id: self.region_id.as_ref().to_owned(),
            name: self.name.as_ref().to_owned(),
        })
    }
}

#[async_trait::async_trait]
impl ActiveModelBehavior for super::_entities::tax_rates::ActiveModel {
    async fn before_save<C>(self, _db: &C, insert: bool) -> Result<Self, DbErr>
    where
        C: ConnectionTrait,
    {
        self.validate()?;
        if insert {
            let mut this = self;
            this.id = ActiveValue::Set(Uuid::new_v4().to_string());
            Ok(this)
        } else {
            Ok(self)
        }
    }
}

impl Model {
    /// finds a tax rate by the provided id
    ///
    /// # Errors
    ///
    /// When could not find tax rate or DB query error
    pub async fn find_by_id(db: &DatabaseConnection, id: &str) -> ModelResult<Self> {
        let tax_rate = tax_rates::Entity::find()
            .filter(
                model::query::condition()
                    .eq(tax_rates::Column::Id, id)
                    .build(),
            )
            .one(db)
            .await?;
        tax_rate.ok_or_else(|| ModelError::EntityNotFound)
    }

    /// finds tax rates by the provided region id
    ///
    /// # Errors
    ///
    /// When could not find tax rates or DB query error
    pub async fn find_by_region_id(
        db: &DatabaseConnection,
        region_id: &str,
    ) -> ModelResult<Vec<Self>> {
        let tax_rates = tax_rates::Entity::find()
            .filter(
                model::query::condition()
                    .eq(tax_rates::Column::RegionId, region_id)
                    .build(),
            )
            .all(db)
            .await?;
        Ok(tax_rates)
    }

    /// Asynchronously creates a tax rate and saves it to the database.
    ///
    /// # Errors
    ///
    /// When could not save the tax rate into the DB
    pub async fn create(db: &DatabaseConnection, params: &CreateParams) -> ModelResult<Self> {
        let tax_rate = tax_rates::ActiveModel {
            region_id: ActiveValue::set(params.region_id.to_string()),
            name: ActiveValue::set(params.name.to_string()),
            r#type: ActiveValue::set(params.r#type.clone()),
            rate: ActiveValue::set(params.rate),
            ..Default::default()
        }
        .insert(db)
        .await?;

        Ok(tax_rate)
    }

    /// Deletes the tax rate
    ///
    /// # Errors
    ///
    /// When could not delete the tax rate from the DB
    pub async fn delete(self, db: &DatabaseConnection) -> ModelResult<DeleteResult> {
        let model: tax_rates::ActiveModel = self.into();
        Ok(model.delete(db).await?)
    }
}

impl ActiveModel {
    /// Updates the tax rate's name
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_name(
        mut self,
        db: &DatabaseConnection,
        name: String,
    ) -> ModelResult<Model> {
        self.name = ActiveValue::set(name);
        Ok(self.update(db).await?)
    }

    /// Updates the tax rate's type
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_type(
        mut self,
        db: &DatabaseConnection,
        r#type: Type,
    ) -> ModelResult<Model> {
        self.r#type = ActiveValue::set(r#type);
        Ok(self.update(db).await?)
    }

    /// Updates the tax rate's rate
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_rate(
        mut self,
        db: &DatabaseConnection,
        rate: Decimal,
    ) -> ModelResult<Model> {
        self.rate = ActiveValue::set(rate);
        Ok(self.update(db).await?)
    }
}
